# coding: utf-8

from elementtree.ElementTree import parse
from catalog.isbn import isValidISBN10, convertISBN10toISBN13 

def parse_gbs_xml(xml):
    u'''Parse file from Google Book Search -> My Library -> Export my library'''
    
    if xml.multiple_chunks():
        raise ValueError(u'This file is too large, please split it.')

    tree = parse(xml)
    elem = tree.getroot()
    
    editions = creators = 0
    items = []

    for book in elem.getiterator('book'):
        edition = {}
        creator_list = []
        for field in list(book):
            key = None
            value = field.text
            if field.tag == 'title':
                key = 'title'
            elif field.tag == 'identifier':
                tag, value = [e.text for e in field]
                if tag == 'ISBN':
                    if isValidISBN10(value):
                        key = 'isbn'
                        value = convertISBN10toISBN13(value)
                else: continue # we will not handle non-ISBN identifiers
            elif field.tag == 'contributor':
                for i, name in enumerate([name.strip() for name in field.text.split(',')]):
                    creator = {'name': name, 'role': '', 'citation_order': i+1}
                    creator_list.append(creator)
                    creators += 1
                key = 'creators'
                value = creator_list
            else:
                continue # we will not handle the GBS url and id fields
            if key is not None:
                edition[key] = value
        items.append(edition)
        editions += 1

    return {'creators':creators, 'editions':editions,
            'name':xml.name, 'size':xml.size, 'contents':items}
